package D4;

import java.util.Arrays;

public class Java03 {
    public static void main(String[] args) {

        //二分查找
        //定义一个数组
        int[] array = new int[]{1,2,3,4,5,6,7,8,9};
        int rs = binarySearch(array,6);
        System.out.println(binarySearch(array,100));
        System.out.println(Arrays.binarySearch(array,9));
    }
    public static int binarySearch(int[] arr,int date){
        //二分查找
        //先定义左边和最右边的数据
        int left = 0;
        int right = arr.length - 1;
        while(left <= right){
            int middle = (left + right) / 2;
            if (date > arr[middle]){
                left = middle + 1;
            }else if (date < arr[middle]){
                right = middle -1;
            }else {
                return middle;
            }
        }
        return -1;
    }
}
